// 当前播放信息存放在本地的变量名
import { Lrc, Runner } from "lrc-kit";
import { getLyric } from "../../api/lyric.js";
import { shallowReactive } from "vue";
import AudioList from "@/utils/audio-list/main.js";
import { formatSeconds, toPlayPage } from "@/utils/utils.js";
import { PLAYNEWPAGENAME, LCI } from "@/utils/constant";
import { getOpfsUrl } from "@/utils/opfs.ts";
import router from "@/router";
import { getShiJiItem } from "@/api/cloudbase-sgbedit.js";
let _info = {};
try {
  _info = JSON.parse(localStorage.getItem(LCI)) || {};
} catch (error) {
  console.log("error-->", error);
}
const audio = {
  namespaced: true,
  state: () => ({
    // 音频元素
    ad: AudioList.create({
      handleUrl: (url) => {
        return getOpfsUrl(url, { mimeType: "audio/*" });
      },
    }),
    // 对应播放面板的ICON状态
    view: {
      playstate: "mdi-play-circle", // 播放器的控制按钮
      playprev: "mdi-skip-previous-circle", // 上一首
      playnext: "mdi-skip-next-circle", // 下一首
      playlist: "mdi-view-list", // 列表按钮
      playSort: "fa-undo", // 播放顺序
      duration: "00:00:00",
      currentDuration: "00:00:00",
      sliderVal: 0,
      currentTime: 0,
    },
    // 所有要显示的ICON图片
    iconText: {
      // 播放组件的图标
      play: "mdi-play-circle", // 播放按钮
      pause: "mdi-pause-circle", // 暂停按钮
      random: "fa-random", // 随机播放按钮
      order: "fa-sort", // 连续播放按钮
      single: "fa-undo", // 单曲播放按钮
      loop: "loop", // 循环播放
      error: "mdi-exclamation-circle",
      none: "queue-stop", // 播放完停止
    },
    // 当前播放音频的信息
    info: _info,
    // 当前播放状态
    paused: true,
    // src准备好后，是否进行播放
    autoPlay: false,
    // 首次加载标志
    firstLoad: false,
    // 即时歌词
    lyric: null,
    runner: null,
    // 当前的歌词
    currentLyric: {},
    settingLyricBtnShow: false,
    analyser: null,
    playerList: [],
  }),
  getters: {
    audio: (state) => state.ad,
    getInfo: (state) => {
      return state.info;
    },
    // 当前播放状态
    getPaused: (state) => state.paused,
    // 获取首次加载标志
    getFirstLoad: (state) => state.firstLoad,
    currentLyric: (state) => state.currentLyric,
  },
  mutations: {
    // 设置当前音频信息
    setInfo: (state, info) => {
      state.info = info;
      localStorage.setItem(LCI, JSON.stringify(info));
      if (router.currentRoute.value.name == PLAYNEWPAGENAME) {
        document.title = info.mulu;
      }
    },

    // 设置是否自动播放
    setAutoPlay: (state, val) => {
      state.autoPlay = val;
    },
    // 设置当前的自动换歌状态
    setViewPlaySort: (state, val) => {
      state.view.playSort = val;
    },
    // 通过外部方法设置播放按钮的状态
    setViewPlayState: (state, val) => {
      state.view.playstate = val;
    },
    setAudio: (state, val) => {
      state.ad = val;
    },
    setAudioPause: (state, val) => {
      state.paused = val;
    },
    setFirstLoad: (state, val) => {
      state.firstLoad = val;
    },
    setSettingLyricBtnShow: (state, val) => {
      state.settingLyricBtnShow = val;
    },
    setAnalyser: (state, val) => {
      state.analyser = val;
    },
  },
  actions: {
    play(state) {
      state.ad.play();
    },

    /**
     * 所有音频的事件，调用 ad元素后。需要调用此方法来激活事件
     * @param state
     * @param events 一个对像包含要回调的事件函数 例 { oncanplay:()=>{} }
     */
    init: ({ commit, state, dispatch }) => {
      AudioList.handleChangeIndexAftre = async (payload) => {
        try {
          const res = await getShiJiItem(payload._id);
          const data = AudioList.transformPlayerList(res, {
            serial: "xuhao",
            src: "dmtUrl.adUrl",
            id: "_id",
            banZouUrl: "dmtUrl.banZouUrl",
          });

          return data;
        } catch (error) {
          console.log("error--?", error);
          return payload;
        }
      };

      AudioList.audioList.addEventListener("canplay", () => {
        state.view.duration = formatSeconds(AudioList.audioList.duration);
      });
      AudioList.audioList.addEventListener("play", () => {
        console.log("播放");
        state.view.playstate = state.iconText.pause;
        const { duration } = AudioList.audioList;
        state.paused = false;
        try {
          const currentTime = (duration * state.view.sliderVal) / 100;
          AudioList.audioList.currentTime = isNaN(currentTime) ? 0 : currentTime;
        } catch (error) {
          console.log("设置播放进度失败", error);
        }
      });

      AudioList.audioList.addEventListener("pause", () => {
        state.paused = true;
        state.view.playstate = state.iconText.play;
      });

      AudioList.audioList.addEventListener("videoListTimeupdate", (e) => {
        const { currentTime } = AudioList.audioList;
        state.view.currentDuration = e.detail.formatCurrentTime; // 设置当前播放的时分秒
        state.view.sliderVal = e.detail.progress; // 设置slider的值
        state.view.currentTime = currentTime; // 设置当前播放时间
      });

      AudioList.audioList.addEventListener("ended", () => {
        state.view.sliderVal = 0;
        state.view.currentDuration = "00:00:00";
        state.currentLyric.index = 0;
      });

      AudioList.audioList.addEventListener("modeChage", (e) => {
        const index = AudioList.modes.findIndex((mode) => mode === e.detail);
        const modeState = [
          state.iconText.single,
          state.iconText.order,
          state.iconText.random,
          state.iconText.loop,
          state.iconText.none,
        ];
        state.view.playSort = modeState[index];
      });

      AudioList.audioList.addEventListener("switchSongs", (event) => {
        const item = event.detail.info;
        commit("setInfo", item);

        if (router.currentRoute.value.name !== PLAYNEWPAGENAME) {
          return;
        }
        toPlayPage(
          {
            _id: item._id,
            shijiIndex: router.currentRoute.value.params.gedanid,
          },
          router.currentRoute.value.params.type,
          "replace",
          router.currentRoute.value.query || {}
        );
      });
      AudioList.audioList.addEventListener("playerListUpdate", (event) => {
        state.playerList = shallowReactive(event.detail);
      });

      AudioList.audioList.addEventListener("changeAudioType", (event) => {
        console.log("changeAudioType-->", event.detail);
      });
    },
  },
};

export default audio;
